/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package czStvDpds.i18n;

import czStvDpds.logging.Logging;
import java.io.File;
import java.io.FileInputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.logging.Level;

/**
 *
 * @author Ondra
 */
public class Internationalization {

    private static Locale currentLocale;
    private static PropertyResourceBundle guiLabels, guiLabelsDefault;
    public static final String DEFAULT_LANGUAGE = "en", DEFAULT_COUNTRY = "GB";

    /**
     * Zmena jazyka v nastaveni hry musi vyvolat tuto metodu
     * 
     * @param language dvoupismenny kod noveho jazyka ve kterem ma byt GUI zobrazeno
     * @param country dvoupismanny kod nove zeme (VELKYMI PISMENY) 
     */
    public static void setLocale(String language, String country) {
        currentLocale = new Locale(language, country);
        createBundle();
    }

    /**
     * Zmena jazyka v nastaveni hry musi vyvolat tuto metodu
     * 
     * @param locale Definice lokalizace (viz vyse)
     */
    public static void setLocale(Locale locale) {
        currentLocale = locale;
        createBundle();
    }

    /**
     * vytvari seznamy prekladu, defaultni (podle GUILabels.properties) a zvoleneho jazyka
     * 
     * @return jestli se nahrani zdarilo
     */
    private static boolean createBundle() {
        if (!createDefaultBundle()) {
            return false;
        }

        String fileName = "lang/GUILabels_" + currentLocale.getLanguage() + "_" + currentLocale.getCountry() + ".properties";
        FileInputStream fis = null;
        URL reference = new Internationalization().getClass().getResource(fileName);
        try {
            fis = new FileInputStream(new File(reference.toURI()));
            guiLabels = new PropertyResourceBundle(fis);
            fis.close();
            return true;
        } catch (Exception ex) {
            Logging.getMainLogger().log(Level.SEVERE, "Failed to load translate files {0}", ex.getLocalizedMessage());
            Logging.flushAllHandlers();
            return false;
        }
    }

    /**
     * volana metodou Internationalization.createBundle(), aby vytvorila defaultni seznam frazi, ktery bude pouzit v pripade neexistence fraze ve zvolenem jazyku
     * 
     * @return jestli se nahrani zdarilo
     */
    private static boolean createDefaultBundle() {
        String fileName = "lang/GUILabels.properties";
        FileInputStream fis = null;
        URL reference = new Internationalization().getClass().getResource(fileName);
        try {
            fis = new FileInputStream(new File(reference.toURI()));
            guiLabelsDefault = new PropertyResourceBundle(fis);
            fis.close();
            return true;
        } catch (Exception ex) {
            Logging.getMainLogger().log(Level.SEVERE, "Failed to load default translate files {0}", ex.getLocalizedMessage());
            Logging.flushAllHandlers();
            return false;
        }
    }

    /**
     * Preklada fraze, nejdulezitejsi metoda
     * 
     * @param key - klic pro frazi definovany v souborech prekladu
     * @return frazi jako String v aktualnim jazyce, pokud se neco nezdari 
     *         (nenajde soubory, soubory neobsahuji klic), vraci "TRANSLATION_FAILED"
     */
    public static String translate(String key) {
        if (guiLabels == null) {
            if (currentLocale == null) {
                currentLocale = new Locale(DEFAULT_LANGUAGE, DEFAULT_COUNTRY);
            }
            if (!createBundle()) {
                if (!createDefaultBundle()) {
                    return "TRANSLATION_FAILED";
                }
            }
        }
        String phrase;
        try {
            phrase = guiLabels.getString(key);
        } catch (MissingResourceException ex) {
            try {
                phrase = guiLabelsDefault.getString(key);
            } catch (MissingResourceException ex2) {
                return "TRANSLATION_FAILED";
            }
        }
        return phrase;
    }

    /**
     * Prohleda soubory a zjisti vsechny dostupne lokalizace
     * 
     * @return vsechny preklady jako instance Locale, <code>null</code> pokud nenajde soubory 
     */
    public static ArrayList<Locale> getAvailableLocalizations() {
        ArrayList<Locale> locs = new ArrayList();
        URL reference = new Internationalization().getClass().getResource("lang");
        File directory;
        try {
            directory = new File(reference.toURI());
        } catch (URISyntaxException ex) {
            return null;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            String name = file.getName();
            if (file.isFile()) {
                String extension = name.substring(name.lastIndexOf('.') + 1);
                if (extension.compareTo("properties") == 0 && name.indexOf("_") != -1 && name.substring(0, name.indexOf("_")).compareTo("GUILabels") == 0) {
                    String language = name.substring(name.indexOf("_") + 1, name.lastIndexOf("_"));
                    String country = name.substring(name.lastIndexOf("_") + 1, name.indexOf("."));
                    locs.add(new Locale(language, country));
                }
            }
        }
        return locs;
    }
}
